package com.boomsecret.juc.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinliang on 2019/1/22.
 */
public class ExecutorServiceDemo {
    private static ExecutorService threadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

    public static void main(String[] args) {
        for (int index = 0; index < 2; index ++) {
            int temp = index;
            threadPool.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(temp + 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread-" + temp);
            });
        }

//        非阻塞方法 关闭线程池(等待已提交线程执行完毕) 不可以再提交线程
        threadPool.shutdown();

//        try {
//            TimeUnit.SECONDS.sleep(8);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        尝试停止所有主动执行的任务 停止等待任务的处理 并返回正在等待执行的任务列表
//        threadPool.shutdownNow();

        try {
            System.out.println("awaitTermination start");
            System.out.println(threadPool.awaitTermination(6, TimeUnit.SECONDS));
            System.out.println("awaitTermination end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("--------------");
        System.out.println(threadPool.isShutdown());
        System.out.println("--------------");
        System.out.println(threadPool.isTerminated());
        System.out.println("主线程执行完毕");
    }
}
